package com.example.sqliteviewer;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

public class TableViewerActivity extends AppCompatActivity {

    private String databasePath;
    private String tableName;
    private SQLiteDatabase database;
    private TableLayout tableLayout;
    private TextView tvRowCount;
    private TextView tvEmptyTable;
    private HorizontalScrollView scrollView;
    private TextView tvSqlQuery;
    private Button btnCopySql;

    // 当前选中的单元格信息
    private String selectedCellValue;
    private int selectedRowIndex = -1;
    private int selectedColumnIndex = -1;

    // 分页相关变量
    private Button btnPrevPage;
    private Button btnNextPage;
    private TextView tvPageInfo;
    private EditText etPageNumber;
    private int currentPage = 1;
    private int pageSize = 50; // 每页显示的记录数
    private int totalRows = 0;
    private int totalPages = 0;

    // 搜索相关变量
    private String searchQuery = "";
    private String[] columnNames;

    // 存储权限请求码
    private static final int STORAGE_PERMISSION_REQUEST_CODE = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_viewer);

        databasePath = getIntent().getStringExtra("DATABASE_PATH");
        tableName = getIntent().getStringExtra("TABLE_NAME");

        if (databasePath == null || tableName == null) {
            Toast.makeText(this, "无效的数据库或表名", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        setTitle(tableName);

        tableLayout = findViewById(R.id.tableLayout);
        tvRowCount = findViewById(R.id.tvRowCount);
        tvEmptyTable = findViewById(R.id.tvEmptyTable);
        scrollView = findViewById(R.id.scrollView);
        EditText etSearch = findViewById(R.id.etSearch);
        tvSqlQuery = findViewById(R.id.tvSqlQuery);
        btnCopySql = findViewById(R.id.btnCopySql);

        // 设置复制SQL按钮点击事件
        btnCopySql.setOnClickListener(v -> {
            String sqlQuery = tvSqlQuery.getText().toString();
            if (!sqlQuery.isEmpty()) {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("SQL查询", sqlQuery);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(this, "SQL查询已复制到剪贴板", Toast.LENGTH_SHORT).show();
            }
        });

        // 初始化分页控件
        btnPrevPage = findViewById(R.id.btnPrevPage);
        btnNextPage = findViewById(R.id.btnNextPage);
        tvPageInfo = findViewById(R.id.tvPageInfo);
        etPageNumber = findViewById(R.id.etPageNumber);
        Button btnGoToPage = findViewById(R.id.btnGoToPage);

        // 设置搜索框监听器
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                searchQuery = s.toString().trim();
                currentPage = 1; // 重置到第一页
                loadTableData();
            }
        });

        // 设置分页按钮点击事件
        btnPrevPage.setOnClickListener(v -> {
            if (currentPage > 1) {
                currentPage--;
                loadTableData();
            }
        });

        btnNextPage.setOnClickListener(v -> {
            if (currentPage < totalPages) {
                currentPage++;
                loadTableData();
            }
        });

        // 设置页码跳转按钮点击事件
        btnGoToPage.setOnClickListener(v -> {
            String pageStr = etPageNumber.getText().toString().trim();
            if (!pageStr.isEmpty()) {
                try {
                    int pageNum = Integer.parseInt(pageStr);
                    if (pageNum > 0 && pageNum <= totalPages) {
                        currentPage = pageNum;
                        loadTableData();
                    } else {
                        Toast.makeText(TableViewerActivity.this,
                                "请输入有效页码 (1-" + totalPages + ")", Toast.LENGTH_SHORT).show();
                    }
                } catch (NumberFormatException e) {
                    Toast.makeText(TableViewerActivity.this, "请输入有效数字", Toast.LENGTH_SHORT).show();
                }
                // 清空输入框
                etPageNumber.setText("");
            }
        });

        loadTableData();
    }

    private void loadTableData() {
        try {
            database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);

            // 获取表结构，使用TableInfoUtils类
            List<ColumnInfo> columnInfoList = TableInfoUtils.getTableColumnInfo(database, tableName);

            if (!columnInfoList.isEmpty()) {
                // 清空表格
                tableLayout.removeAllViews();

                // 创建表头
                TableRow headerRow = new TableRow(this);
                headerRow.setBackgroundColor(ContextCompat.getColor(this, R.color.header_background));

                // 添加行号列
                TextView rowNumHeader = createTextView("#", true);
                headerRow.addView(rowNumHeader);

                // 添加列名
                int columnCount = columnInfoList.size();
                columnNames = new String[columnCount];
                int index = 0;

                for (ColumnInfo columnInfo : columnInfoList) {
                    String columnName = columnInfo.getName();
                    columnNames[index++] = columnName;

                    TextView headerText = createTextView(columnName, true);
                    headerRow.addView(headerText);
                }

                tableLayout.addView(headerRow);

                // 构建查询语句
                StringBuilder queryBuilder = new StringBuilder();
                queryBuilder.append("SELECT * FROM ").append(tableName);

                // 如果有搜索条件，添加WHERE子句
                if (!searchQuery.isEmpty()) {
                    StringJoiner joiner = new StringJoiner(" OR ");
                    for (String columnName : columnNames) {
                        joiner.add(columnName + " LIKE '%" + searchQuery + "%'");
                    }
                    if (joiner.length() != 0) {
                        queryBuilder.append(" WHERE ").append(joiner);
                    }
                }

                // 获取总记录数
                Cursor cursor = database.rawQuery("SELECT COUNT(*) FROM (" + queryBuilder + ")", null);
                if (cursor.moveToFirst()) {
                    totalRows = cursor.getInt(0);
                }
                cursor.close();

                // 计算总页数
                totalPages = (int) Math.ceil((double) totalRows / pageSize);

                // 更新分页信息
                updatePaginationControls();

                // 添加分页限制
                int offset = (currentPage - 1) * pageSize;
                queryBuilder.append(" LIMIT ").append(pageSize).append(" OFFSET ").append(offset);

                // 显示完整SQL查询语句（包括分页部分）
                tvSqlQuery.setText(queryBuilder.toString());

                // 执行最终查询
                cursor = database.rawQuery(queryBuilder.toString(), null);

                tvRowCount.setText("总行数: " + totalRows + " (当前显示第 " + (offset + 1) + "-" +
                        (offset + Math.min(pageSize, cursor.getCount())) + " 行)");

                if (cursor.getCount() > 0 && cursor.moveToFirst()) {
                    // 显示数据行
                    int rowNum = offset + 1;
                    do {
                        TableRow dataRow = new TableRow(this);

                        // 设置交替行背景色
                        if (rowNum % 2 == 0) {
                            dataRow.setBackgroundColor(ContextCompat.getColor(this, R.color.row_even));
                        } else {
                            dataRow.setBackgroundColor(ContextCompat.getColor(this, R.color.row_odd));
                        }

                        // 添加行号
                        TextView rowNumText = createTextView(String.valueOf(rowNum), false);
                        dataRow.addView(rowNumText);

                        // 添加数据
                        for (String columnName : columnNames) {
                            int columnIndex = cursor.getColumnIndex(columnName);
                            String value = "";

                            if (columnIndex != -1 && !cursor.isNull(columnIndex)) {
                                switch (cursor.getType(columnIndex)) {
                                    case Cursor.FIELD_TYPE_INTEGER:
                                        value = String.valueOf(cursor.getLong(columnIndex));
                                        break;
                                    case Cursor.FIELD_TYPE_FLOAT:
                                        value = String.valueOf(cursor.getDouble(columnIndex));
                                        break;
                                    case Cursor.FIELD_TYPE_STRING:
                                        value = cursor.getString(columnIndex);
                                        break;
                                    case Cursor.FIELD_TYPE_BLOB:
                                        value = "[BLOB]";
                                        break;
                                    case Cursor.FIELD_TYPE_NULL:
                                        value = "NULL";
                                        break;
                                }
                            } else {
                                value = "NULL";
                            }

                            TextView dataText = createTextView(value, false);

                            // 为每个单元格设置标记，记录其行列位置和列名
                            dataText.setTag(R.id.tag_row_index, rowNum);
                            dataText.setTag(R.id.tag_column_index, columnIndex);
                            dataText.setTag(R.id.tag_column_name, columnName);

                            dataRow.addView(dataText);
                        }

                        tableLayout.addView(dataRow);
                        rowNum++;

                    } while (cursor.moveToNext());

                    tvEmptyTable.setVisibility(View.GONE);
                    scrollView.setVisibility(View.VISIBLE);
                } else {
                    // 表为空
                    tvEmptyTable.setVisibility(View.VISIBLE);
                    scrollView.setVisibility(View.GONE);
                }

                cursor.close();
            } else {
                Toast.makeText(this, "无法获取表结构", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            Toast.makeText(this, "加载表数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    private void updatePaginationControls() {
        // 更新页码信息
        tvPageInfo.setText("第 " + currentPage + "/" + totalPages + " 页");

        // 更新按钮状态
        btnPrevPage.setEnabled(currentPage > 1);
        btnNextPage.setEnabled(currentPage < totalPages);
    }

    private TextView createTextView(String text, boolean isHeader) {
        TextView textView = new TextView(this);
        textView.setText(text);
        textView.setPadding(16, 16, 16, 16);

        if (isHeader) {
            textView.setTextColor(ContextCompat.getColor(this, R.color.header_text));
            textView.setTypeface(null, Typeface.BOLD);
        } else {
            textView.setTextColor(ContextCompat.getColor(this, R.color.data_text));

            // 为数据单元格添加长按监听器
            textView.setOnLongClickListener(v -> {
                showCellContextMenu(textView, text);
                return true;
            });
        }

        return textView;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_table_viewer, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_add_record) {
            showAddRecordDialog();
            return true;
        } else if (id == R.id.action_export_csv) {
            exportTableToCSV();
            return true;
        } else if (id == R.id.action_export_json) {
            exportTableToJSON();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void exportTableToCSV() {
        // 检查存储权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    STORAGE_PERMISSION_REQUEST_CODE);
            return;
        }

        // 执行导出
        String filePath = ExportUtils.exportTableToCSV(this, databasePath, tableName, searchQuery);

        if (filePath != null) {
            Toast.makeText(this, "导出成功: " + filePath, Toast.LENGTH_LONG).show();
        }
    }

    private void exportTableToJSON() {
        // 检查存储权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    STORAGE_PERMISSION_REQUEST_CODE);
            return;
        }

        // 执行导出
        String filePath = JsonExportUtils.exportTableToJSON(this, databasePath, tableName, searchQuery);

        if (filePath != null) {
            Toast.makeText(this, "导出成功: " + filePath, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限获取成功，执行导出
                exportTableToCSV();
            } else {
                Toast.makeText(this, "需要存储权限才能导出文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 显示单元格上下文菜单
     *
     * @param view      单元格视图
     * @param cellValue 单元格值
     */
    private void showCellContextMenu(TextView view, String cellValue) {
        // 保存当前选中的单元格信息
        selectedCellValue = cellValue;
        selectedRowIndex = (int) view.getTag(R.id.tag_row_index);
        selectedColumnIndex = (int) view.getTag(R.id.tag_column_index);
        String columnName = (String) view.getTag(R.id.tag_column_name);

        // 创建弹出菜单
        PopupMenu popupMenu = new PopupMenu(this, view);
        popupMenu.getMenu().add(Menu.NONE, 1, Menu.NONE, "复制");
        popupMenu.getMenu().add(Menu.NONE, 2, Menu.NONE, "编辑");

        // 设置菜单项点击事件
        popupMenu.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case 1: // 复制
                    copyCellValue(cellValue);
                    return true;
                case 2: // 编辑
                    showEditDialog(columnName, cellValue);
                    return true;
                default:
                    return false;
            }
        });

        // 显示菜单
        popupMenu.show();
    }

    /**
     * 复制单元格值到剪贴板
     *
     * @param value 要复制的值
     */
    private void copyCellValue(String value) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("单元格数据", value);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(this, "已复制到剪贴板", Toast.LENGTH_SHORT).show();
    }

    /**
     * 显示编辑对话框
     *
     * @param columnName   列名
     * @param currentValue 当前值
     */
    private void showEditDialog(String columnName, String currentValue) {
        // 创建输入框
        final EditText input = new EditText(this);
        input.setText(currentValue);

        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("编辑 " + columnName)
                .setView(input)
                .setPositiveButton("保存", (dialog, which) -> {
                    String newValue = input.getText().toString();
                    updateCellValue(columnName, newValue);
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        // 显示对话框
        builder.show();
    }

    /**
     * 更新单元格值
     *
     * @param columnName 列名
     * @param newValue   新值
     */
    private void updateCellValue(String columnName, String newValue) {
        try {
            // 获取当前页的偏移量
            int offset = (currentPage - 1) * pageSize;

            // 获取当前行的主键信息
            List<ColumnInfo> columnInfoList = TableInfoUtils.getTableColumnInfo(database, tableName);
            List<String> primaryKeys = new ArrayList<>();

            for (ColumnInfo columnInfo : columnInfoList) {
                if (columnInfo.isPrimaryKey()) {
                    primaryKeys.add(columnInfo.getName());
                }
            }

            // 如果没有主键，使用所有列作为条件
            if (primaryKeys.isEmpty()) {
                Toast.makeText(this, "无法更新：表没有主键", Toast.LENGTH_SHORT).show();
                return;
            }

            // 获取当前行的数据
            StringBuilder queryBuilder = new StringBuilder();
            queryBuilder.append("SELECT * FROM ").append(tableName);

            // 添加搜索条件（如果有）
            if (!searchQuery.isEmpty()) {
                queryBuilder.append(" WHERE ");
                for (int i = 0; i < columnNames.length; i++) {
                    if (i > 0) {
                        queryBuilder.append(" OR ");
                    }
                    queryBuilder.append(columnNames[i]).append(" LIKE '%").append(searchQuery).append("%'");
                }
            }

            // 添加分页限制
            queryBuilder.append(" LIMIT 1 OFFSET ").append(offset + selectedRowIndex - 1);

            Cursor cursor = database.rawQuery(queryBuilder.toString(), null);

            if (cursor.moveToFirst()) {
                // 创建更新条件
                StringBuilder whereClause = new StringBuilder();
                List<String> whereArgs = new ArrayList<>();

                for (String key : primaryKeys) {
                    if (whereClause.length() > 0) {
                        whereClause.append(" AND ");
                    }
                    whereClause.append(key).append("=?");
                    whereArgs.add(cursor.getString(cursor.getColumnIndex(key)));
                }

                // 创建更新内容
                ContentValues values = new ContentValues();
                values.put(columnName, newValue);

                // 执行更新
                int rowsAffected = database.update(
                        tableName,
                        values,
                        whereClause.toString(),
                        whereArgs.toArray(new String[0]));

                if (rowsAffected > 0) {
                    Toast.makeText(this, "更新成功：" + rowsAffected, Toast.LENGTH_SHORT).show();
                    // 重新加载数据
                    loadTableData();
                } else {
                    Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
                }
            }

            cursor.close();

        } catch (Exception e) {
            Toast.makeText(this, "更新失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示添加记录对话框
     */
    private void showAddRecordDialog() {
        try {
            // 获取表结构信息
            List<ColumnInfo> columnInfoList = TableInfoUtils.getTableColumnInfo(database, tableName);
            if (columnInfoList.isEmpty()) {
                Toast.makeText(this, "无法获取表结构信息", Toast.LENGTH_SHORT).show();
                return;
            }

            // 创建对话框视图
            View dialogView = getLayoutInflater().inflate(R.layout.dialog_add_record, null);
            LinearLayout formContainer = dialogView.findViewById(R.id.formContainer);

            // 创建输入控件的映射，用于后续获取输入值
            final Map<String, View> inputViewMap = new HashMap<>();

            // 为每个字段创建输入控件
            for (ColumnInfo columnInfo : columnInfoList) {
                String columnName = columnInfo.getName();
                String columnType = columnInfo.getType().toUpperCase();
                boolean isNotNull = columnInfo.isNotNull();
                boolean isPrimaryKey = columnInfo.isPrimaryKey();
                String defaultValue = columnInfo.getDfltValue();

                // 如果是自增主键，则跳过（用户不需要输入）
                if (isPrimaryKey && columnType.contains("INTEGER") && 
                    (defaultValue == null || defaultValue.isEmpty())) {
                    continue;
                }

                // 创建字段标签
                TextView labelView = new TextView(this);
                labelView.setText(columnName + (isNotNull ? " *" : ""));
                labelView.setTypeface(null, Typeface.BOLD);
                labelView.setPadding(0, 8, 0, 4);
                formContainer.addView(labelView);

                // 根据字段类型创建不同的输入控件
                View inputView;

                if (columnType.contains("TEXT")) {
                    // 文本输入框
                    EditText editText = new EditText(this);
                    editText.setHint("输入" + columnName);
                    if (defaultValue != null && !defaultValue.isEmpty()) {
                        editText.setText(defaultValue.replace("'", ""));
                    }
                    inputView = editText;
                } else if (columnType.contains("INTEGER") || columnType.contains("REAL") || 
                           columnType.contains("NUMERIC") || columnType.contains("FLOAT") || 
                           columnType.contains("DOUBLE")) {
                    // 数字输入框
                    EditText editText = new EditText(this);
                    editText.setInputType(InputType.TYPE_CLASS_NUMBER | 
                                         (columnType.contains("REAL") || 
                                          columnType.contains("FLOAT") || 
                                          columnType.contains("DOUBLE") || 
                                          columnType.contains("NUMERIC") ? 
                                          InputType.TYPE_NUMBER_FLAG_DECIMAL : 0));
                    editText.setHint("输入" + columnName);
                    if (defaultValue != null && !defaultValue.isEmpty()) {
                        editText.setText(defaultValue);
                    }
                    inputView = editText;
                } else if (columnType.contains("BOOLEAN")) {
                    // 布尔值选择器
                    CheckBox checkBox = new CheckBox(this);
                    checkBox.setText("是/否");
                    if (defaultValue != null && !defaultValue.isEmpty()) {
                        checkBox.setChecked(defaultValue.equals("1") || 
                                           defaultValue.toLowerCase().equals("true"));
                    }
                    inputView = checkBox;
                } else if (columnType.contains("BLOB")) {
                    // BLOB类型提示
                    TextView blobNotice = new TextView(this);
                    blobNotice.setText("[BLOB类型暂不支持直接输入]");
                    blobNotice.setTextColor(Color.GRAY);
                    inputView = blobNotice;
                } else {
                    // 默认使用文本输入框
                    EditText editText = new EditText(this);
                    editText.setHint("输入" + columnName);
                    if (defaultValue != null && !defaultValue.isEmpty()) {
                        editText.setText(defaultValue.replace("'", ""));
                    }
                    inputView = editText;
                }

                // 设置布局参数
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                params.setMargins(0, 0, 0, 16);
                inputView.setLayoutParams(params);

                // 添加到容器并保存到映射中
                formContainer.addView(inputView);
                inputViewMap.put(columnName, inputView);
            }

            // 创建对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("新增记录")
                   .setView(dialogView)
                   .setPositiveButton("保存", (dialog, which) -> {
                       // 收集输入的值并插入记录
                       insertNewRecord(columnInfoList, inputViewMap);
                   })
                   .setNegativeButton("取消", (dialog, which) -> dialog.cancel());

            // 显示对话框
            builder.show();

        } catch (Exception e) {
            Toast.makeText(this, "创建表单失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 插入新记录
     *
     * @param columnInfoList 列信息列表
     * @param inputViewMap   输入控件映射
     */
    private void insertNewRecord(List<ColumnInfo> columnInfoList, Map<String, View> inputViewMap) {
        try {
            // 创建ContentValues对象存储字段值
            ContentValues values = new ContentValues();
            boolean hasValidationError = false;

            // 收集每个字段的输入值
            for (ColumnInfo columnInfo : columnInfoList) {
                String columnName = columnInfo.getName();
                String columnType = columnInfo.getType().toUpperCase();
                boolean isNotNull = columnInfo.isNotNull();
                boolean isPrimaryKey = columnInfo.isPrimaryKey();
                
                // 如果是自增主键，则跳过
                if (isPrimaryKey && columnType.contains("INTEGER") && 
                    (columnInfo.getDfltValue() == null || columnInfo.getDfltValue().isEmpty())) {
                    continue;
                }
                
                // 获取输入控件
                View inputView = inputViewMap.get(columnName);
                if (inputView == null) continue;
                
                // 根据控件类型获取值
                String inputValue = null;
                
                if (inputView instanceof EditText) {
                    inputValue = ((EditText) inputView).getText().toString().trim();
                } else if (inputView instanceof CheckBox) {
                    inputValue = ((CheckBox) inputView).isChecked() ? "1" : "0";
                } else if (inputView instanceof TextView) {
                    // BLOB类型或其他不支持直接输入的类型
                    continue;
                }
                
                // 验证必填字段
                if (isNotNull && (inputValue == null || inputValue.isEmpty())) {
                    Toast.makeText(this, columnName + " 是必填字段", Toast.LENGTH_SHORT).show();
                    hasValidationError = true;
                    break;
                }
                
                // 根据字段类型设置值
                if (inputValue != null && !inputValue.isEmpty()) {
                    if (columnType.contains("INTEGER")) {
                        try {
                            values.put(columnName, Long.parseLong(inputValue));
                        } catch (NumberFormatException e) {
                            Toast.makeText(this, columnName + " 必须是整数", Toast.LENGTH_SHORT).show();
                            hasValidationError = true;
                            break;
                        }
                    } else if (columnType.contains("REAL") || columnType.contains("FLOAT") || 
                               columnType.contains("DOUBLE") || columnType.contains("NUMERIC")) {
                        try {
                            values.put(columnName, Double.parseDouble(inputValue));
                        } catch (NumberFormatException e) {
                            Toast.makeText(this, columnName + " 必须是数字", Toast.LENGTH_SHORT).show();
                            hasValidationError = true;
                            break;
                        }
                    } else {
                        values.put(columnName, inputValue);
                    }
                }
            }
            
            // 如果没有验证错误，执行插入操作
            if (!hasValidationError) {
                long newRowId = database.insert(tableName, null, values);
                
                if (newRowId != -1) {
                    Toast.makeText(this, "记录添加成功", Toast.LENGTH_SHORT).show();
                    // 重新加载表格数据
                    loadTableData();
                } else {
                    Toast.makeText(this, "记录添加失败", Toast.LENGTH_SHORT).show();
                }
            }
            
        } catch (Exception e) {
            Toast.makeText(this, "插入记录失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (database != null && database.isOpen()) {
            database.close();
        }
    }
}